package com.xxxx.yeb.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.yeb.mapper.EmployeeMapper;
import com.xxxx.yeb.pojo.Employee;
import com.xxxx.yeb.pojo.EmployeeQuery;
import com.xxxx.yeb.pojo.RespBean;
import com.xxxx.yeb.service.IEmployeeService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2020-07-17
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    private DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    /**
     * 多条件选择查询员工信息
     *
     * @param employeeQuery
     * @return
     */
    public EmployeeQuery selectAllEmployeeByQuery(EmployeeQuery employeeQuery) {
        Page<Employee> page = new Page<>(employeeQuery.getCurrentPage(), employeeQuery.getSize());
        IPage<Employee> employeeIPage = employeeMapper.selectAllEmployeeByQuery(page, employeeQuery);
        employeeQuery.setTotal(employeeIPage.getTotal());
        employeeQuery.setData(employeeIPage.getRecords());
        return employeeQuery;
    }

    public EmployeeQuery selectAllEmployeeSal(EmployeeQuery employeeQuery) {
        Page<Employee> page = new Page<>(employeeQuery.getCurrentPage(), employeeQuery.getSize());
        IPage<Employee> employeeIPage = employeeMapper.selectAllEmployeeSal(page, employeeQuery);
        employeeQuery.setTotal(employeeIPage.getTotal());
        employeeQuery.setData(employeeIPage.getRecords());
        employeeQuery.toString();
        return employeeQuery;
    }

    /**
     * 查询最大员工
     *
     * @return
     */
    public EmployeeQuery queryMaxWorkID() {
        return employeeMapper.queryMaxWorkID();
    }

    /**
     * 编辑员工信息
     *
     * @param employee 员工对象
     * @return 返回确认信息
     */
    public RespBean updateEmployeeByEmp(Employee employee) {
        Employee employee1 = checkContractTerm(employee);
        Integer num = employeeMapper.updateEmployeeByEmp(employee1);
        if (num == null || num == 0) {
            return RespBean.error("系统异常,更新失败");
        }
        return RespBean.success("编辑成功");
    }

    /**
     * 添加员工信息
     *
     * @param employee 员工对象
     * @return 返回确认信息
     */
    public RespBean insertEmployeeByEmp(Employee employee) {
        Employee employee1 = checkContractTerm(employee);
        Integer num = employeeMapper.insertEmployeeByEmp(employee1);
        if (num == null || num == 0) {
            return RespBean.error("系统异常,添加失败");
        }
        return RespBean.success("添加成功");
    }


    /**
     * 删除员工信息
     *
     * @param id 待删除员工id
     * @return 确认消息
     */
    public RespBean deleteEmployeeById(Integer id) {
        List<Integer> list = new ArrayList<>();
        list.add(id);
        int num = employeeMapper.deleteBatchIds(list);
        if (num == 0) {
            return RespBean.error("系统异常,删除失败");
        }
        return RespBean.success("删除成功");
    }

    /**
     * 导出所有员工信息
     */
    public void excelExport(HttpServletResponse response) throws IOException {
        //表头数据
        String[] header = {"姓名", "工号", "性别", "出生日期", "身份证号码", "婚姻状况", "民族", "籍贯", "政治面貌", "电子邮件", "电话号码", "联系地址", "所属部门", "职称", "职位", "聘用形式", "最高学历", "毕业院校", "专业", "在职状态", "入职日期", "转正日期", "合同起始日期", "合同截止日期", "合同期限(年)"};

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格，设置表格名称为"员工表"
        HSSFSheet sheet = workbook.createSheet("员工表");
        //设置表格列宽度为10个字节
        sheet.setDefaultColumnWidth(10);
        //创建标题的显示样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //创建第一行表头
        HSSFRow headrow = sheet.createRow(0);

        //遍历添加表头(下面模拟遍历员工，也是同样的操作过程)
        for (int i = 0; i < header.length; i++) {
            //创建一个单元格
            HSSFCell cell = headrow.createCell(i);

            //创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(header[i]);

            //将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
            cell.setCellStyle(headerStyle);
        }

        //获取所有的employee
        List<Employee> emps = employeeMapper.selectAllEmployee();
        for (int i = 0; i < emps.size(); i++) {
            //创建一行
            HSSFRow row1 = sheet.createRow(i + 1);
            //第2列姓名
            row1.createCell(0).setCellValue(new HSSFRichTextString(emps.get(i).getName()));
            //第3列工号
            row1.createCell(1).setCellValue(new HSSFRichTextString(emps.get(i).getWorkID()));
            // 第4列性别
            row1.createCell(2).setCellValue(new HSSFRichTextString(emps.get(i).getGender()));
            //第5列出生日期
            if (emps.get(i).getBirthday() != null) {
                row1.createCell(3).setCellValue(new HSSFRichTextString(dateFormat.format(emps.get(i).getBirthday())));
            }
            //第6列身份证号码
            row1.createCell(4).setCellValue(new HSSFRichTextString(emps.get(i).getIdCard()));
            //第7列婚姻状况
            row1.createCell(5).setCellValue(new HSSFRichTextString(emps.get(i).getWedlock()));
            //第8列民族
            row1.createCell(6).setCellValue(new HSSFRichTextString(emps.get(i).getNationName()));
            //第9列籍贯
            row1.createCell(7).setCellValue(new HSSFRichTextString(emps.get(i).getNativePlace()));
            //第10列政治面貌
            row1.createCell(8).setCellValue(new HSSFRichTextString(emps.get(i).getPoliticsStatusName()));
            //第11列电子邮件
            row1.createCell(9).setCellValue(new HSSFRichTextString(emps.get(i).getEmail()));
            //第12列电话号码
            row1.createCell(10).setCellValue(new HSSFRichTextString(emps.get(i).getPhone()));
            //第13列联系地址
            row1.createCell(11).setCellValue(new HSSFRichTextString(emps.get(i).getAddress()));
            //第14列所属部门
            row1.createCell(12).setCellValue(new HSSFRichTextString(emps.get(i).getDepartmentName()));
            //第15列职称
            row1.createCell(13).setCellValue(new HSSFRichTextString(emps.get(i).getJobLevelName()));
            //第16列职位
            row1.createCell(14).setCellValue(new HSSFRichTextString(emps.get(i).getPositionName()));
            //第17列聘用形式
            if (emps.get(i).getEngageForm() != null) {
                row1.createCell(15).setCellValue(new HSSFRichTextString(emps.get(i).getEngageForm()));
            }
            //第18列最高学历
            if (emps.get(i).getTiptopDegree() != null) {
                row1.createCell(16).setCellValue(new HSSFRichTextString(emps.get(i).getTiptopDegree()));
            }
            //第19列 毕业院校
            row1.createCell(17).setCellValue(new HSSFRichTextString(emps.get(i).getSchool()));
            //第20列所属专业
            row1.createCell(18).setCellValue(new HSSFRichTextString(emps.get(i).getSpecialty()));
            //第21列 在职状态
            row1.createCell(19).setCellValue(new HSSFRichTextString(emps.get(i).getWorkState()));

            //第21列入职日期
            if (emps.get(i).getBeginDate() != null) {
                row1.createCell(20).setCellValue(new HSSFRichTextString(dateFormat.format(emps.get(i).getBeginDate())));
            }
            //第22列转正日期
            if (emps.get(i).getConversionTime() != null) {
                row1.createCell(21).setCellValue(new HSSFRichTextString(dateFormat.format(emps.get(i).getConversionTime())));
            }
            //第23列合同起始日期
            if (emps.get(i).getBeginContract() != null) {
                row1.createCell(22).setCellValue(new HSSFRichTextString(dateFormat.format(emps.get(i).getBeginContract())));
            }
            //第24列合同截止日期
            if (emps.get(i).getEndContract() != null) {
                row1.createCell(23).setCellValue(new HSSFRichTextString(dateFormat.format(emps.get(i).getEndContract())));
            }
//            第25列合同期限
            if (emps.get(i).getContractTerm() != null) {
                row1.createCell(24).setCellValue(new HSSFRichTextString(emps.get(i).getContractTerm().toString()));
            }

        }

        response.setCharacterEncoding("utf-8");
        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        //这后面可以设置导出Excel的名称，此例中名为student.xls
        response.setHeader("Content-disposition", "attachment;filename=employee.xls");

        //刷新缓冲
        response.flushBuffer();

        //workbook将Excel写入到response的输出流中，供页面下载
        workbook.write(response.getOutputStream());
    }

    /**
     * 判断合同期限
     *
     * @param employee
     * @return 返回设置了新合同期限的员工对象
     */
    private Employee checkContractTerm(Employee employee) {
        // 计算日期差值
        long lnum = employee.getEndContract().toEpochDay() - employee.getBeginContract().toEpochDay();
        // 保留两位小数
        BigDecimal b = new BigDecimal((double) lnum / 365);
        Double contractTerm = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        employee.setContractTerm(contractTerm);
        return employee;
    }

    /**
     * 通过员工id更新工资账套
     *
     * @param employeeQuery
     * @return
     */
    public RespBean updateEmployeeSal(EmployeeQuery employeeQuery) {
        int num = employeeMapper.updateEmployeeSal(employeeQuery);
        if (num < 1) {
            return RespBean.error("工资账套更改失败!");
        }
        return RespBean.success("工资账套更改成功!");
    }
}

